local desc_qdz__1v2 = [[
  # 抢地主欢乐斗地主模式简介
 
  ## 选择框来自水天一色大佬~

  ## 与欢乐斗地主的区别是可抢地主，也会显示是谁在选择倍率。

  ## 另外，存在人机时，选2倍或3倍则会直接成为地主

  下面是欢乐斗地主的规则：

  总体规则类似身份局。游戏由三人进行，一人扮演地主（主公），其他两人扮演农民（反贼）。

  地主选将框+2，增加1点体力上限和体力，且拥有以下额外技能：

  - **飞扬**：判定阶段开始时，你可以弃置两张手牌并弃置自己判定区内的一张牌。

  - **跋扈**：锁定技，准备阶段，你摸一张牌；出牌阶段，你可以多使用一张【杀】。

  当农民被击杀后，另一名农民可以选择：摸两张牌，或者回复1点体力。

  *击杀农民的人没有摸三张牌的奖励。*

  胜利规则与身份局一致。

]]

--[[
迷你、game机制分析
loadData 跟普通对话框差不多
通过ClientInstance.notifyServer("PushRequest", "updatemini,select," + root.selected);
这个返回调用minigame的 update_func，弃置data是用逗号隔开的select，等
然后大概是用更新doNotify("UpdateMiniGame", json.encode(data))
--]]

-- 对该qml及MiniGame的理解
-- 调用MiniGame时会将服务端的信息传给qml，qml会先处理所有键值表，但是能点击按钮的只有一个，
-- 然后要在addMiniGame里设置更新下一个可以点按钮的角色并传给qml，然后两边的信息是用json传递的，所以同样要用json才能得到数据。
-- 另外，qml如果得到了3倍的信息就会直接关闭，所以要想达到通知哪个角色选择了几倍的效果，最好是直接写在qml里。
-- 然而我发现写在qml却只有第一个选倍率的人能看到。。toast.show似乎不怎么管用，于是我发现了另一个方法，即下面的在update_func里和开始miniGame时通知。

Fk:addMiniGame {
  name = "qdz__1v2_selectdizhu",
  qml_path = "packages/testmode/qml/ChooseGeneralfor1v2",
  default_choice = function(player, data) --默认值
    local x = math.random(1,3)
    return x
  end,
  update_func = function(player, data)
    local room = player.room
    local b = player.next._splayer:getScreenName()
    local pname = player._splayer:getScreenName()
    local x = json.encode(data)
    local n
    if type(json.decode(x)) == "table" and #json.decode(x) >= 2 then
      n = json.decode(x)[2] or " "
    end
    for i, p in ipairs(room.players) do
      p:doNotify("UpdateMiniGame", json.encode(data))
      if n ~= "3" then
        p:doNotify("ShowToast", ""..pname.."选择了"..n.."倍")
        p:doNotify("ShowToast", "当前正在选择倍率的玩家是"..b.."")
      else
        p:doNotify("ShowToast", ""..pname.."选择了3倍抢地主！")
      end
    end
  end,
}

local qdz__1v2_getLogic = function()
  local qdz__1v2_logic = GameLogic:subclass("qdz__1v2_logic")

  function qdz__1v2_logic:initialize(room)
    GameLogic.initialize(self, room)
    self.role_table = { nil, nil, { "lord", "rebel", "rebel" }, }
  end

  function qdz__1v2_logic:assignRoles()
    local room = self.room
    local n = #room.players
    room:setBanner("@[:]qdzmode_rule","qdz__1v2-intro")
    local roles = self.role_table[n]
    table.shuffle(roles)

    for i = 1, n do
      local p = room.players[i]
      p.role = roles[i]
    end

  end

  function qdz__1v2_logic:adjustSeats()
    local player_circle = {}
    local room = self.room
    local players = self.room.players
    local p = 1
    for i = 1, #players do
      if players[i].role == "lord" then
        p = i
        break
      end
    end
    for j = p, #players do
      table.insert(player_circle, players[j])
    end
    for j = 1, p - 1 do
      table.insert(player_circle, players[j])
    end

    self.room:arrangeSeats(player_circle)
  end

  function qdz__1v2_logic:chooseGenerals()
    local room = self.room ---@type Room
    local generalNum = room.settings.generalNum
    local n = room.settings.enableDeputy and 2 or 1
    local players = room.players
    local maylord = players[math.random(1,#players)]
    local lord
    maylord.role = "lord"
    room:setCurrent(maylord)
    local generals = room:getNGenerals(#players * generalNum + 2)
    ---有ai不参与叫地主
    local maxpoint = 1
    local noai = table.filter(players, function(p) return p.id > 0 end)
    if #noai ~= 3 then
      room:doBroadcastNotify("ShowToast", Fk:translate("#qdz__1v2_mode_findai"))
    end
    room:sendLog{ type = "#qdz_1v2_seat_tips", toast = true }
    room:delay(2000)
    local data_table = {}
    local noai_data_table = {}
    local sortplayers = {}  --对玩家排序,不然迷你游戏会有问题,各个玩家的武将也可能会重复
    for _, p in ipairs(noai) do
      table.insert(sortplayers, p)
    end
    for _, p in ipairs(players) do
      if not table.contains(noai, p) then
        table.insert(sortplayers, p)
      end
    end
    for i, p in ipairs(sortplayers) do  --用排序后的玩家列表
      local start_index = (i - 1) * generalNum + 1
      local end_index = i * generalNum + 1
      local pname = p._splayer:getScreenName()
      data_table[p.id] = {
        generals = table.slice(generals, start_index, end_index),
        enable = i, ---- 玩家次序
        index = 1,  ---- 当前次序
        pname = pname, ----玩家名称
      }
      if table.contains(noai, p) then
        noai_data_table[p.id] = data_table[p.id]
      end
    end
    room:doBroadcastNotify("ShowToast", "当前正在选择倍率的玩家是"..noai_data_table[sortplayers[1].id].pname.."")
    room:askToMiniGame(noai, {
      skill_name = "qdz__1v2_selectdizhu",
      game_type = "qdz__1v2_selectdizhu",
      data_table = noai_data_table
    })
    --得分最高者为地主,否则为原来的随机地主
    for i, p in ipairs(noai) do
      local point = p.reply_ready and json.decode(p.client_reply) or p.default_reply
      if point > maxpoint then
        maxpoint = point
        lord = p
      end
      if #noai ~= 3 and point ~= 2 and point ~= 3 then  ----存在人机且不为2倍或3倍则为随机地主
        lord = maylord
      end
    end

    --设置倍率
    room:setBanner("@qdz__1v2_mode_POINT", maxpoint)

    ----分配身份和座位
    for i, p in ipairs(players) do
      if p.id == lord.id then
        p.role = "lord"
      else
        p.role = "rebel"
      end
    end

    for _, p in ipairs(players) do
      room:setPlayerProperty(p, "role_shown", true)
      room:broadcastProperty(p, "role")
    end

    ----队友手牌
    -- local nonlord = room:getOtherPlayers(lord)
    -- nonlord[1]:addBuddy(nonlord[2])
    -- nonlord[2]:addBuddy(nonlord[1])

    --这时候再调一下位置  ----调位置还是放这吧
    local player_circle = {}
    local x = 1
    for i = 1, #players do
      if players[i].role == "lord" then
        x = i
        break
      end
    end
    for j = x, #players do
      table.insert(player_circle, players[j])
    end
    for j = 1, x - 1 do
      table.insert(player_circle, players[j])
    end

    room:arrangeSeats(player_circle)

    --这时候正式开始选将
    local req = Request:new(players, "AskForGeneral")
    for i, p in ipairs(players) do
      local arg = data_table[p.id].generals  ---直接从data_table中获取玩家看到的自己的武将
      if p.role == "lord" then
        local count = #generals ---- 地主多发两个武将
        table.insert(arg, generals[count])
        table.insert(arg, generals[count - 1])
      end
      req:setData(p, { arg, n })
      req:setDefaultReply(p, table.random(arg, n))
    end
    req:ask()
    for _, p in ipairs(players) do
      local result = req:getResult(p)
      local general, deputy = result[1], result[2]
      room:prepareGeneral(p, general, deputy)
    end
    room:askToChooseKingdom(players)

    for _, p in ipairs(players) do
      room:broadcastProperty(p, "general")
    end

  end

  function qdz__1v2_logic:attachSkillToPlayers()
    local room = self.room
    local addRoleModSkills = function(player, skillName)
      local skill = Fk.skills[skillName]
      if not skill then
        fk.qCritical("Skill: " .. skillName .. " doesn't exist!")
        return
      end
      if skill:hasTag(Skill.Lord) then
        return
      end
      if skill:hasTag(Skill.AttachedKingdom) and not table.contains(skill:getSkeleton().attached_kingdom, player.kingdom) then
        return
      end
      room:handleAddLoseSkills(player, skillName, nil, false)
    end
    for _, p in ipairs(room.alive_players) do
      for _, s in ipairs(Fk.generals[p.general]:getSkillNameList(false)) do
        addRoleModSkills(p, s)
      end
      local deputy = Fk.generals[p.deputyGeneral]
      if deputy then
        for _, s in ipairs(deputy:getSkillNameList(false)) do
          addRoleModSkills(p, s)
        end
      end
      if p.role == "lord" then
        room:handleAddLoseSkills(p, "m_feiyang|m_bahu", nil, false)
      end
    end
  end

  return qdz__1v2_logic
end


local qdz__1v2_mode = fk.CreateGameMode {
  name = "qdz__1v2_mode",
  minPlayer = 3,
  maxPlayer = 3,
  logic = qdz__1v2_getLogic,
  main_mode = "1v2_mode",
  is_counted = function(self, room)
    return #room.players >= 2
  end,
  surrender_func = function(self, playedTime)
    local surrenderJudge = { { text = "time limitation: 1 min", passed = playedTime >= 60 } }
    if Self.role ~= "lord" then
      table.insert(surrenderJudge, { text = "1v2: left you alive", passed = #Fk:currentRoom().alive_players == 2 })
    end
    return surrenderJudge
  end,
  get_adjusted = function(self, player)
    if player.role == "lord" then
      return { hp = player.hp + 1, maxHp = player.maxHp + 1 }
    end
    return {}
  end,
  reward_punish = function(self, victim, killer)
    local room = victim.room
    if victim.role == "rebel" then
      for _, p in ipairs(room:getOtherPlayers(victim)) do
        if p.role == "rebel" then
          local choices = { "draw2", "Cancel" }
          if p:isWounded() then
            table.insert(choices, 2, "recover")
          end
          local choice = room:askToChoice(p, {
            choices = choices,
            skill_name = "PickLegacy",
          })
          if choice == "draw2" then
            p:drawCards(2, "game_rule")
          else
            room:recover {
              who = p,
              num = 1,
              recoverBy = p,
              skillName = "game_rule",
            }
          end
        end
      end
    end
  end,
}

Fk:loadTranslationTable {
  ["qdz__1v2_mode"] = "抢地主斗地主",
  ["#qdz__1v2_rule"] = "挑选遗产",
  ["qdz__1v2-intro"] = "抢地主斗地主",
  [":qdz__1v2-intro"] = [[
  <br>总体规则类似身份局。游戏由三人进行，一人扮演地主（主公），其他两人扮演农民（反贼）。

  <br>地主选将框+2，增加1点体力上限和体力，且拥有以下额外技能：

  <br>飞扬：判定阶段开始时，你可以弃置两张手牌并弃置自己判定区内的一张牌。

  <br>跋扈：锁定技，准备阶段，你摸一张牌；出牌阶段，你可以多使用一张【杀】。

  <br>当农民被击杀后，另一名农民可以选择：摸两张牌，或者回复1点体力。

  <br>击杀农民的人没有摸三张牌的奖励。

  <br>胜利规则与身份局一致。

  <br><b>可抢地主且农民手牌互相可见，选择择框来自水天一色大佬（小改了一下）~</b>

  ]],
  ["$LookGeneral"] = "右键或长按可查看武将技能，你的倍率是？",
  ["@[:]qdzmode_rule"]="模式",  
  ["qdz__1v2_selectdizhu"] = "选择地主",
  ["@qdz__1v2_mode_POINT"] = "本局倍率",
  ["#qdz__1v2_mode_findai"] = "本局存在人机，不选2倍或3倍则为随机地主",
  ["#qdz_1v2_seat_tips"] = "温馨提示：正在选择倍率的角色若成为地主，则其下家为2号位、上家为3号位",

  ["$thechoosingplayer"] = "当前正在选择倍率的玩家是 %1",
  ["$thechoosingresult_3"] = "%1 选择了3倍抢地主！",
  ["$thechoosingresult"] = "%1 选择了%2倍",

  [":qdz__1v2_mode"] = desc_qdz__1v2,
}

return qdz__1v2_mode
